<template>
  <draggable
    v-model="node.children"
    item-key="id"
    class="draggable-node"
    group="nodeGroup"
    handle=".draggable-node"
    :animation="200"
    @add="added"
  >
    <template #item="{ element }">
      <avc-page-comp
        :id="element.id"
        :node="element"
        :inputParam="props.inputParam"
        @mouseoverNode="mouseoverNode"
        @activeNode="activeNode"
        @deleteNode="deleteNode"
      />
    </template>
  </draggable>
</template>

<script setup>
import draggable from 'vuedraggable';

const emit = defineEmits(['activeNode', 'deleteNode', 'mouseoverNode']);
const props = defineProps({
  type: String,
  inputParam: Object
});
const node = defineModel();

const added = (e) => {
  if (props.type !== '大屏') return;
  const newNode = node.value.children[e.newIndex];
  if (!newNode) return;
  if (newNode.currStyle) {
    setIndexAndSort(newNode);
  } else {
    setTimeout(() => setIndexAndSort(newNode), 1000);
  }
};

const setIndexAndSort = (newNode) => {
  let maxIndex = 0;
  node.value.children.forEach(item => {
    if (!item.currStyle) {
      item.currStyle = {};
    }
    if (!item.currStyle?.['z-index']) {
      item.currStyle['z-index'] = 0;
    }
    maxIndex = (item.currStyle['z-index'] || 0) > maxIndex ? item.currStyle['z-index'] : maxIndex;
  });
  newNode.currStyle['z-index'] = maxIndex + 1;
  node.value.children = node.value.children.sort((a, b) => a.currStyle['z-index'] - b.currStyle['z-index']);
  node.value.children.forEach((item, index) => {
    item.currStyle['z-index'] = index;
  });
};

const activeNode = (node) => {
  emit('activeNode', node);
};

const deleteNode = (item) => {
  emit('deleteNode', item, node.value.children);
};

const mouseoverNode = (item) => {
  emit('mouseoverNode', item)
};
</script>

<style scoped lang="scss">
.draggable-node {
  width: 100%;
}
</style>